package com.hellobike.haxing.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.hellobike.haxing.order.result.Result;
import com.hellobike.haxing.request.user.LocationParam;
import com.hellobike.haxing.search.vo.SearchLocationVo;
import com.hellobike.haxing.user.ILocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class LocationServiceImpl implements ILocationService {

    @Autowired
    private RestTemplate restTemplate;

    private String locationSearchUrl =
            "https://apis.map.qq.com/ws/geocoder/v1/?location=%f,%f&key=%s";

    @Value("${location.key}")
    private String key;


    @Override
    public Result<SearchLocationVo> saveLocation(LocationParam location) {
        Result<SearchLocationVo> locationVoResult = new Result<>();
        JSONObject jsonObject = restTemplate.getForObject(String.format(locationSearchUrl, location.getLat(), location.getLon(), key), JSONObject.class);
        if (jsonObject.getIntValue("status") == 0) {
            SearchLocationVo locationVo = new SearchLocationVo();
            locationVo.setLat(location.getLat());
            locationVo.setLon(location.getLon());
            JSONObject result = jsonObject.getJSONObject("result");
            JSONObject addressComponent = result.getJSONObject("address_component");
            JSONObject addressReference = result.getJSONObject("address_reference");
            locationVo.setProvinceName(addressComponent.getString("province"));
            locationVo.setCityName(addressComponent.getString("city"));
            locationVo.setDistrictName(addressComponent.getString("district"));
            locationVo.setStreetName(addressReference.getJSONObject("town").getString("title"));
            locationVoResult.setData(locationVo);
        }
        return locationVoResult;
    }
}
